package com.uniview.utils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * created by lux 06609
 * modify by lw7573
 * jackson常用工具类
 */
@Slf4j
public class JacksonUtils {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * bean转json
     */
    public static String beanToJson(Object obj) throws IOException {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
        mapper.writeValue(gen, obj);
        gen.close();
        return sw.toString();
    }

    /**
     * json转bean
     */
    public static <T> T jsonToBean(String jsonStr, Class<T> objClass)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(jsonStr, objClass);
    }

    /**
     * map转json
     */
    public static String mapToJson(Map<String, Object> map) {
        ObjectMapper mapper = new ObjectMapper();
        String string = null;
        try {
            string = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            log.error(e.toString(), e);
        }
        return string;
    }

    /**
     * json转map
     */
    public static Map<String, Object> jsonToMap(String str) {
        ObjectMapper mapper = new ObjectMapper();
        Map readValue = null;
        try {
            readValue = mapper.readValue(str, Map.class);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return readValue;

    }

    /**
     * object 转 json
     *
     * @param object
     * @return
     */
    public static String objectToJson(Object object) {
        String str = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            str = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error(e.toString(), e);
        }
        return str;
    }
}
